package com.jwgf.smarowindingmachine_unity.ui;


import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.fragment.app.DialogFragment;

import com.jwgf.Half485.fxthreadpool.FxCommandManager;
import com.jwgf.Half485.modbusthreadpool.ModbusCommandManager;
import com.jwgf.Half485.modbusthreadpool.PLCData;
import com.jwgf.can.CanThread;
import com.jwgf.common.AppContext;
import com.jwgf.common.ViewCache;
import com.jwgf.fault.FaultRecorder;
import com.jwgf.faultnavigation.PictureDialog;
import com.jwgf.mqtt.MqttClientManager;
import com.jwgf.smarowindingmachine_unity.R;
import com.jwgf.smarowindingmachine_unity.logic.MachineParameterSharedPreference;
import com.jwgf.smarowindingmachine_unity.logic.SmaroWindingMachineModBusReadParser;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;

import static android.content.Context.ACTIVITY_SERVICE;

public class TitleFragment extends BaseFragment {
    public static final String fragmentTag = "TitleFragment";
    private View v;
    private TextView date;
    private TextView stitle;
    private SimpleDateFormat formatter;
    private ImageButton btn_ethernet_state;
    private ImageButton btn_can_state;
    private ImageButton btn_half485_state;
    private ImageButton btn_shortcut1;
    private ImageButton btn_shortcut2;
    private ImageButton btn_shortcut3;
    private ImageButton btn_help;
    private TextView machineNo;
    private SwitchPageManager spm = SwitchPageManager.getInstance();
    private LockDialog lockDialog;

    private PictureDialog cbfAlarmDialog;
    private HashMap<Integer, Integer> cbfCodeMap;

    private SharedPreferences sp = AppContext.getInstance()
            .getSharedPreferences("ShortCutSetting", Context.MODE_PRIVATE);
    private MachineParameterSharedPreference paraSp = MachineParameterSharedPreference.getInstance();

    private Disposable disposable;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v = ViewCache.getInstance().getView(R.layout.fragment_title);
        cbfCodeMap = new HashMap<>();
        cbfCodeMap.put(4 << 24 | 331 << 8 | 0, R.drawable.cbf_alarm_331_0);
        cbfCodeMap.put(4 << 24 | 331 << 8 | 3, R.drawable.cbf_alarm_331_3);
        cbfCodeMap.put(4 << 24 | 331 << 8 | 5, R.drawable.cbf_alarm_331_5);
        cbfCodeMap.put(5 << 24 | 352 << 8 | 8, R.drawable.cbf_alarm_352_8);
        cbfCodeMap.put(5 << 24 | 352 << 8 | 9, R.drawable.cbf_alarm_352_9);
        cbfCodeMap.put(5 << 24 | 352 << 8 | 10, R.drawable.cbf_alarm_352_10);
        cbfCodeMap.put(5 << 24 | 352 << 8 | 11, R.drawable.cbf_alarm_352_11);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        btn_ethernet_state = (ImageButton) v
                .findViewById(R.id.btn_ethernet_state);
        btn_can_state = (ImageButton) v.findViewById(R.id.btn_can_state);
        btn_half485_state = (ImageButton) v
                .findViewById(R.id.btn_half485_state);

        date = (TextView) v.findViewById(R.id.title_date);
        formatter = new SimpleDateFormat("HH:mm  yyyy-MM-dd", Locale.US);
        formatter.setTimeZone(TimeZone.getDefault());
        String now = formatter.format(Calendar.getInstance().getTime());
        date.setText(now);
        stitle = (TextView) v.findViewById(R.id.server_state);
        stitle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                DialogFragment dialog = new TitleBarDialog();
                Bundle bd = new Bundle();
                ArrayList<Integer> faultList = SmaroWindingMachineModBusReadParser.getInstance().getCurrentFaultList();
                bd.putIntegerArrayList(TitleBarDialog.KEY, faultList);
                dialog.setArguments(bd);
                dialog.show(getFragmentManager(), "Fault_popup");
            }
        });


        btn_shortcut1 = (ImageButton) v.findViewById(R.id.btn_shortcut1);
        if (spm.loadShortCutIcon1() != null) {
            btn_shortcut1.setImageDrawable(spm.loadShortCutIcon1());
        }
        btn_shortcut1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                spm.shortCut1Action(getFragmentManager());
            }
        });
        btn_shortcut1.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                spm.setShortCut1(getActivity());
                btn_shortcut1.setImageDrawable(spm.loadShortCutIcon1());
                return true;
            }
        });
        btn_shortcut2 = (ImageButton) v.findViewById(R.id.btn_shortcut2);
        if (spm.loadShortCutIcon2() != null) {
            btn_shortcut2.setImageDrawable(spm.loadShortCutIcon2());
        }
        btn_shortcut2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                spm.shortCut2Action(getFragmentManager());
            }
        });
        btn_shortcut2.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                spm.setShortCut2(getActivity());
                btn_shortcut2.setImageDrawable(spm.loadShortCutIcon2());
                return true;
            }
        });
        btn_shortcut3 = (ImageButton) v.findViewById(R.id.btn_shortcut3);
        if (spm.loadShortCutIcon3() != null) {
            btn_shortcut3.setImageDrawable(spm.loadShortCutIcon3());
        }
        btn_shortcut3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                spm.shortCut3Action(getFragmentManager());
            }
        });
        btn_shortcut3.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                spm.setShortCut3(getActivity());
                btn_shortcut3.setImageDrawable(spm.loadShortCutIcon3());
                return true;
            }
        });
        btn_help = (ImageButton) v.findViewById(R.id.btn_help);
        btn_help.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//                DialogFragment help = new HelpDialog();
//                help.show(getFragmentManager(), "help");
//                DialogFragment help = new QRCodeDialog();
//                Bundle bundle = new Bundle();
//                bundle.putString(QRCodeDialog.CONTENT, "http://test.jwrx.net:29000/HmiUpdate/manuel/20200115显控.pdf");
//                help.setArguments(bundle);
//                help.show(getFragmentManager(), "help");
            }
        });
        machineNo = getActivity().findViewById(R.id.machine_no);


        btn_ethernet_state.setImageResource(R.drawable.ethernet_error);
        btn_can_state.setImageResource(R.drawable.can_error);
        btn_half485_state.setImageResource(R.drawable.half485_error);

    }

    @Override
    public void onResume() {
        super.onResume();
        disposable = createDisposable();
    }

    @Override
    public void onPause() {
        super.onPause();
        disposable.dispose();
    }

    private void UpdateTimeUI() {
        formatter.setTimeZone(TimeZone.getDefault());
        String now = formatter.format(Calendar.getInstance().getTime());
        date.setText(now);
        machineNo.setText(paraSp.getValue(MachineParameterSharedPreference.SYSTEM_MACHINE_NUM, "1"));
    }

    private void refreshBackground() {
        if (SmaroWindingMachineModBusReadParser.getInstance()
                .getCurrentFaultList().isEmpty()) {
//            v.setBackgroundDrawable(AppContext.getInstance().getResources().getDrawable(R.drawable.status_1));
            v.setBackgroundColor(getResources().getColor(R.color.blue));
            if (stitle != null)
                stitle.setText(R.string.none);
            v.setClickable(false);

        } else {
//            v.setBackgroundDrawable(AppContext.getInstance().getResources().getDrawable(R.drawable.status_2));
            v.setBackgroundColor(Color.rgb(0xe3, 0x49, 0x59));

            if (stitle != null)
                stitle.setText(R.string.fault_record);
            v.setClickable(true);
        }
    }

    private Disposable createDisposable() {
        return Observable.interval(3, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Throwable {
                        UpdateTimeUI();
                        if (!CanThread.getInstance().canState()) {
                            btn_can_state.setImageResource(R.drawable.can_error);
                        } else {
                            btn_can_state.setImageResource(R.drawable.can_ok);
                        }
                        if (!MqttClientManager.getInstance().isConnected()) {
                            btn_ethernet_state.setImageResource(R.drawable.ethernet_error);
                        } else {
                            btn_ethernet_state.setImageResource(R.drawable.ethernet_ok);
                        }
                        if (!ModbusCommandManager.getInstance().isComOK() || !FxCommandManager.getInstance().isComOK()) {
                            btn_half485_state.setImageResource(R.drawable.half485_error);
                        } else {
                            btn_half485_state.setImageResource(R.drawable.half485_ok);
                        }
                        refreshBackground();

                        if (PLCData.getInstance() != null) {
                            int isLock = PLCData.getInstance().getHoldingRegister(1, 2500) & 0x800;
                            if (lockDialog != null
                                    && lockDialog.getDialog() != null
                                    && lockDialog.getDialog().isShowing()
                                    && !lockDialog.isRemoving()) {
                                //dialog is showing
                                if (isLock == 0) {
                                    lockDialog.dismiss();
                                }
                            } else {
                                //dialog is not showing
                                if (isLock != 0) {
                                    lockDialog = new LockDialog();
                                    lockDialog.show(getFragmentManager(), "lock_dialog");
                                }
                            }
                        }

                        List<Integer> curFault = SmaroWindingMachineModBusReadParser.getInstance().getCurrentFaultList();
                        for (Integer code : curFault) {
                            if (cbfCodeMap.containsKey(code)) {
                                if (cbfAlarmDialog != null
                                        && cbfAlarmDialog.getDialog() != null
                                        && cbfAlarmDialog.getDialog().isShowing()
                                        && !cbfAlarmDialog.isRemoving()) {
//                                    cbfAlarmDialog.dismiss();
                                } else {
                                    //dialog is not showing
                                    int isYes = Integer.parseInt(MachineParameterSharedPreference.getInstance()
                                            .getValue(MachineParameterSharedPreference.CBF_ALARM, "0"));
                                    if (isYes == 1) {
                                        cbfAlarmDialog = new PictureDialog();
                                        Bundle args = new Bundle();
                                        args.putInt(PictureDialog.KEY, cbfCodeMap.get(code));
                                        args.putString(PictureDialog.TITLE, FaultRecorder.getInstance().getFault(code));
                                        cbfAlarmDialog.setArguments(args);
                                        cbfAlarmDialog.show(getFragmentManager(), "PictureDialog");
                                    }

                                }
                            }
                            break;
                        }

                        if (AppContext.isDebug) {
                            ActivityManager activityManager = (ActivityManager) getActivity().getSystemService(ACTIVITY_SERVICE);
                            //最大分配内存
                            int memory = activityManager.getMemoryClass();
                            Log.d("memory", "memory: " + memory);
                            //最大分配内存获取方法2
                            float maxMemory = (float) (Runtime.getRuntime().maxMemory() * 1.0 / (1024 * 1024));
                            //当前分配的总内存
                            float totalMemory = (float) (Runtime.getRuntime().totalMemory() * 1.0 / (1024 * 1024));
                            //剩余内存
                            float freeMemory = (float) (Runtime.getRuntime().freeMemory() * 1.0 / (1024 * 1024));
                            Log.d("memory", "maxMemory: " + maxMemory);
                            Log.d("memory", "totalMemory: " + totalMemory);
                            Log.d("memory", "freeMemory: " + freeMemory);
                        }
                    }
                });
    }

    public static class CBFAlarm{
        public int code;
        public int pictureId;

        public CBFAlarm(int code, int pictureId) {
            this.code = code;
            this.pictureId = pictureId;
        }
    }
}
